//
//  ChooseCityController.m
//  OnionHome
//
//  Created by fengjie on 2019/9/19.
//  Copyright © 2019 FengJie. All rights reserved.
//选择城市列表

#import "ChooseCityController.h"
#import "CityGroupCell.h"
#import "CityHeaderView.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import <UITableView+SCIndexView.h>
#import <SCIndexView.h>

@interface ChooseCityController ()<CityGroupCellDelegate,CLLocationManagerDelegate>
/**
 *  记录所有城市信息，用于搜索
 */
@property (nonatomic, strong) NSMutableArray *recordCityData;
/**
 *  定位城市
 */
@property (nonatomic, strong) NSMutableArray *localCityData;
/**
 *  热门城市
 */
@property (nonatomic, strong) NSMutableArray *hotCityData;
@property (nonatomic, strong) NSMutableArray *arraySection;
@property(nonatomic,retain)CLLocationManager *locationManager;

@end

NSString *const cityHeaderView = @"CityHeaderView";
NSString *const cityGroupCell = @"CityGroupCell";
NSString *const cityCell = @"CityCell";


@implementation ChooseCityController

-(void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = KWhiteColor;
    [self cityDatas];
    [self createNavTitle];
    [self locationStart];
    [self createTableView];
}
-(void)createNavTitle{
    [self.navigationItem setTitle:@"地区选择"];
    UIBarButtonItem *cancelBarButton =[[UIBarButtonItem alloc] initWithImage:IMAGE_NAMED(@"back") style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonDown:)];
    [self.navigationItem setLeftBarButtonItem:cancelBarButton];
}
-(void)createTableView{
    [self.tableView setSectionIndexBackgroundColor:[UIColor whiteColor]];
    [self.tableView setSectionIndexColor:UIColorFromRGB(0x009966)];
//    [self.tableView setSectionIndexColor:UIColorFromRGB(0x009966)];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cityCell];
    [self.tableView registerClass:[CityGroupCell class] forCellReuseIdentifier:cityGroupCell];
    [self.tableView registerClass:[CityHeaderView class] forHeaderFooterViewReuseIdentifier:cityHeaderView];
    self.tableView.separatorColor = SeparatorColor;
    self.tableView.backgroundColor = KWhiteColor;
    
}
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.cityDatas.count +2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section < 2) {
        return 1;
    }
    CityGroup *group = [self.cityDatas objectAtIndex:section - 2];
    return group.arrayCitys.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section < 2) {
        CityGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:cityGroupCell];
        
        if (indexPath.section == 0) {
            cell.leftImage.image = IMAGE_NAMED(@"home_loction");
            cell.titleLabel.text = @"定位城市";
            cell.noDataLabel.text = @"无法定位当前城市，请稍后再试";
            [cell setCityArray:self.localCityData];
        }
        else {
            cell.leftImage.image = IMAGE_NAMED(@"home_host");
            cell.titleLabel.text = @"热门城市";
            [cell setCityArray:self.hotCityData];
        }
        [cell setDelegate:self];
        return cell;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cityCell];
    CityGroup *group = [self.cityDatas objectAtIndex:indexPath.section - 2];
    CityObject *city =  [group.arrayCitys objectAtIndex:indexPath.row];
    cell.textLabel.textColor = UIColorFromRGB(0x454F44);
    cell.textLabel.font = PingFangSC_Regular(16);
    [cell.textLabel setText:city.cityName];
    
    return cell;
}

#pragma mark UITableViewDelegate
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section < 2 ) {
        UIView * view = UIView.new;
        view.backgroundColor = UIColorFromRGB(0xF5F7F5);
        return view;
    }
    CityHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cityHeaderView];
    NSString *title = [_arraySection objectAtIndex:section ];
    headerView.titleLabel.text = title;
    headerView.titleLabel.backgroundColor = KWhiteColor;
    headerView.backgroundColor = KWhiteColor;
    return headerView;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = UIView.new;
    view.backgroundColor = UIColorFromRGB(0xF5F7F5);

    return view;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return [CityGroupCell getCellHeightOfCityArray:self.localCityData];
    }else if (indexPath.section == 1){
        return [CityGroupCell getCellHeightOfCityArray:self.hotCityData];
    }
    return 44.0f;
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section < 2 ) {
        if (section == 1) {
            return 8.0f;
        }
        return 0.0f;
    }
    return 23.5f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1) {
        return 8.0f;
    }
    return 0.01f;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CityObject *city = nil;
    
    if (indexPath.section < 2) {
        if (indexPath.section == 0 && self.localCityData.count <= 0) {
            [self locationStart];
        }
        return;
    }
    CityGroup *group = [self.cityDatas objectAtIndex:indexPath.section - 2];
    city =  [group.arrayCitys objectAtIndex:indexPath.row];
    
    [self didSelctedCity:city];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.arraySection;
}

- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    DLog(@"%@ -- %zd",title,index);
    if(index == 0){
        return index;
    }
//    return index - 1;
    return index;

}

#pragma mark GYZCityGroupCellDelegate
- (void) cityGroupCellDidSelectCity:(CityObject *)city
{
    [self didSelctedCity:city];
}

#pragma mark - Event Response
- (void) cancelButtonDown:(UIBarButtonItem *)sender{
    if (_delegate && [_delegate respondsToSelector:@selector(cityPickerControllerDidCancel:)]) {
        [_delegate cityPickerControllerDidCancel:self];
    }
}
#pragma mark - Private Methods
- (void) didSelctedCity:(CityObject *)city
{
    if (_delegate && [_delegate respondsToSelector:@selector(cityPickerController:didSelectCity:)]) {
        [_delegate cityPickerController:self didSelectCity:city];
    }
}

//开始定位
-(void)locationStart{
    //判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init] ;
        self.locationManager.delegate = self;
        //设置定位精度
        self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters;//每隔多少米定位一次（这里的设置为每隔百米)
        //使用应用程序期间允许访问位置数据
        [self.locationManager requestWhenInUseAuthorization];
        // 开始定位
        [self.locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
        DLog(@"%@",@"定位服务当前可能尚未打开，请设置打开！");
        
    }
}
#pragma mark - CoreLocation Delegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
//系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
        [self.locationManager stopUpdatingLocation];
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count >0)
         {
             CLPlacemark *placemark = [array objectAtIndex:0];
             //获取城市
             NSString *currCity = placemark.locality;
             if (!currCity) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 currCity = placemark.administrativeArea;
             }
             if (self.localCityData.count <= 0) {
                 CityObject *city = [[CityObject alloc] init];
                 city.cityName = currCity;
                 city.shortName = currCity;
                 [self.localCityData addObject:city];
                 
                 [self.tableView reloadData];
             }
             
         } else if (error ==nil && [array count] == 0)
         {
             DLog(@"No results were returned.");
         }else if (error !=nil)
         {
             DLog(@"An error occurred = %@", error);
         }
         
     }];
    
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    if (error.code ==kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
    
}

-(NSMutableArray *) cityDatas{
    if (_cityDatas == nil) {
        NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"CityData" ofType:@"plist"]];
        _cityDatas = [[NSMutableArray alloc] init];
        for (NSDictionary *groupDic in array) {
            CityGroup *group = [[CityGroup alloc] init];
            group.groupName = [groupDic objectForKey:@"initial"];
            for (NSDictionary *dic in [groupDic objectForKey:@"citys"]) {
                CityObject *city = [[CityObject alloc] init];
                city.cityID = [dic objectForKey:@"city_key"];
                city.cityName = [dic objectForKey:@"city_name"];
                city.shortName = [dic objectForKey:@"short_name"];
                city.pinyin = [dic objectForKey:@"pinyin"];
                city.initials = [dic objectForKey:@"initials"];
                [group.arrayCitys addObject:city];
                [self.recordCityData addObject:city];
            }
            [self.arraySection addObject:group.groupName];
            [_cityDatas addObject:group];
        }
    }
    return _cityDatas;
}
- (NSMutableArray *) recordCityData{
    if (_recordCityData == nil) {
        _recordCityData = [[NSMutableArray alloc] init];
    }
    return _recordCityData;
}
- (NSMutableArray *) localCityData{
    if (_localCityData == nil) {
        _localCityData = [[NSMutableArray alloc] init];
//        if (self.locationCityID != nil) {
//            CityObject *city = nil;
//            for (CityObject *item in self.recordCityData) {
//                if ([item.cityID isEqualToString:self.locationCityID]) {
//                    city = item;
//                    break;
//                }
//            }
//            if (city == nil) {
//                DLog(@"Not Found City: %@", self.locationCityID);
//            }
//            else {
//                [_localCityData addObject:city];
//            }
//        }
    }
    return _localCityData;
}
- (NSMutableArray *) hotCityData{
    if (_hotCityData == nil) {
        _hotCityData = [[NSMutableArray alloc] init];
        for (NSString *str in self.hotCitys) {
            CityObject *city = nil;
            for (CityObject *item in self.recordCityData) {
                if ([item.cityID isEqualToString:str]) {
                    city = item;
                    break;
                }
            }
            if (city == nil) {
                DLog(@"Not Found City: %@", str);
            }
            else {
                [_hotCityData addObject:city];
            }
        }
    }
    return _hotCityData;
}
- (NSMutableArray *) arraySection{
    if (_arraySection == nil) {
        _arraySection = [[NSMutableArray alloc] initWithObjects: @"定位", @"热门", nil];
    }
    return _arraySection;
}
@end
